package org.qqcui.designpattern.patterns.singleton.doublecheck;

/**
 * 双重检查的实现方式，既能够保证线程安全，同时能够满足效率和懒加载，在生产环境推荐使用该方式
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2020-10-16 22:05
 **/
public class SingletonTest06 {

	public static void main(String[] args) {
		System.out.println("双重检查方式，线程安全方式");
		Singleton6 instance1 = Singleton6.getInstance();
		Singleton6 instance2 = Singleton6.getInstance();

		System.out.println(instance1 == instance2);

		System.out.println("instance1.hashCode=" + instance1.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}
}

class Singleton6 {
	/**
	 * 增加了 volatile 关键字，保证可见性和禁止指令重排序，保证创建出的对象是单例的并且是初始化完整的
	 */
	private static volatile Singleton6 instance;

	private Singleton6() {}

	public static Singleton6 getInstance() {
		if (instance == null) {
			synchronized (Singleton6.class) {
				if (instance == null) {
					instance = new Singleton6();
				}
			}
		}
		return instance;
	}
}